package pc

import (
	. "chess_platform/internal/common"
	"chess_platform/models/client"
	"fmt"
	"time"
)

//[pc]测试接口,请勿对接
type TestController struct {
	BaseController
}

func (b *TestController) URLMapping() {

}

// @Title 处理楼层,使其兼容
// @Description 处理楼层,使其兼容
// @Success 0 {string} token
// @Failure 400
// @Failure 404
// @router /handle-club-floor [get]
func (b *TestController) HandleClubFloor() {
	code := b.GetString("secret_code")
	if code != "good_man" {
		b.ResponseFail("you are wrong")
		return
	}
	clubId := b.GetString("club_id")
	LogPc.Debug(fmt.Sprintf("获取到的secret_code=%v,club_id=%v", code, clubId))
	err := HandleClubFloor(clubId)
	if err != nil {
		b.ResponseFail(err.Error())
		return
	}
	b.ResponseSuccess()
}

type ClubInfo2 struct {
	ClubId     int64  `json:"club_id"`
	GameId     int64  `json:"game_id"`
	PlayRule   string `json:"play_rule"`
	PlayOption string `json:"play_option"`
	TableNum   int64  `json:"table_num"`
}

func HandleClubFloor(clubId string) error {
	var count int64 //先统计有多少个没有解散的亲友圈
	sqlCount := fmt.Sprintf(`
		SELECT
			COUNT(1)
		FROM
			%v
		WHERE
			status != %v
	`, TableClub, ClubDismiss)
	o := NewDBOrm(DBChess)
	o.Raw(sqlCount).QueryRow(&count)
	if count == 0 { //没有亲友圈，统计毛线
		LogPc.Info("暂时没有亲友圈可以统计")
		return nil
	}
	var sqlClub string
	if clubId == "" {
		sqlClub = fmt.Sprintf(`
		SELECT
			id AS club_id,game_id,play_rule,play_option,table_num
		FROM
			%v
		WHERE
			status != %v
		LIMIT ?,?
	`, TableClub, ClubDismiss) //已经解散的亲友圈不要统计了
	} else {
		sqlClub = fmt.Sprintf(`
		SELECT
			id AS club_id,game_id,play_rule,play_option,table_num
		FROM
			%v
		WHERE
			status != %v AND id = %v
		LIMIT ?,?
	`, TableClub, ClubDismiss, clubId) //已经解散的亲友圈不要统计了
	}
	//每次取10个,不足10个就有多少取多少

	var i, index, size int64
	size = 10
	for index = 1; i < count; index++ {
		var clubInfo []ClubInfo2
		limit := (index - 1) * size
		n, err := o.Raw(sqlClub, limit, size).QueryRows(&clubInfo)
		if err != nil {
			return err
		}
		//n才是真实取了多少个
		i = limit + n
		err = handleClubFloor(clubInfo)
		if err != nil {
			return err
		}
	}
	return nil
}

func handleClubFloor(clubInfo []ClubInfo2) error {
	for _, v := range clubInfo {
		if v.GameId == 0 {
			continue
		}
		data := map[string]interface{}{
			"club_id":     v.ClubId,
			"game_id":     v.GameId,
			"play_rule":   v.PlayRule,
			"play_option": v.PlayOption,
			"is_delete":   0, //楼层是否已经删除了,1-是, 0-否
			"create_time": time.Now().Unix(),
		}
		_, err := client.NewClubFloor(data)
		if err != nil {
			return err
		}
	}
	return nil
}
